import random
import pygame

bullet_speed = 2
bullet_fire_speed = 10
hero_move_speed = 5
back_move_speed = 2
enemy_come_speed = 10
hero_invincible = True

SCREEN_RECT = pygame.Rect(0, 0, 480, 700)
ENEMY_EVENT = pygame.USEREVENT
FIRE_BULLET_EVENT = pygame.USEREVENT+1
WAKE_FLAME_EVENT = pygame.USEREVENT+2
FPS = 60


class GameSpirits(pygame.sprite.Sprite):

    def __init__(self, image, speed=1):
        super().__init__()
        self.image = pygame.image.load(image)
        self.rect = self.image.get_rect()
        self.speed = speed

    def update(self):
        self.rect.y += self.speed


class BackGround(GameSpirits):

    def __init__(self, is_two=False):
        super().__init__("./images/background.png", back_move_speed)
        if is_two:
            self.rect.bottom = 0

    def update(self):
        super().update()
        if self.rect.y >= SCREEN_RECT.bottom:
            self.rect.bottom = SCREEN_RECT.top


class EnemySpirit(GameSpirits):

    def __init__(self):
        super().__init__("./images/enemy1.png")
        self.speed = random.randint(1, 3)
        self.rect.x = random.randint(0, SCREEN_RECT.width-self.rect.width)

    def update(self):
        super().update()
        if self.rect.y >= SCREEN_RECT.bottom:
            self.kill()


class Hero(GameSpirits):

    def __init__(self):
        super().__init__("./images/me1.png")
        self.rect.centerx = SCREEN_RECT.centerx
        self.rect.y = SCREEN_RECT.bottom - 200
        self.bullet_group = pygame.sprite.Group()
        self.is_two = False

    def update(self):

        press = pygame.key.get_pressed()

        if press[pygame.K_LEFT]:
            self.rect.x -= hero_move_speed
        elif press[pygame.K_RIGHT]:
            self.rect.x += hero_move_speed
        elif press[pygame.K_UP]:
            self.rect.y -= hero_move_speed
        elif press[pygame.K_DOWN]:
            self.rect.y += hero_move_speed

        if self.rect.left <= SCREEN_RECT.left:
            self.rect.left = SCREEN_RECT.left
        elif self.rect.right >= SCREEN_RECT.width:
            self.rect.right = SCREEN_RECT.width

    def fire(self):
        bullet = Bullet()
        bullet.rect.centerx = self.rect.centerx
        bullet.rect.y = self.rect.top
        self.bullet_group.add(bullet)

    def wake_flame(self):
        if self.is_two:
            self.image = pygame.image.load("./images/me1.png")
            self.is_two = False
        else:
            self.image = pygame.image.load("./images/me2.png")
            self.is_two = True




class Bullet(GameSpirits):

    def __init__(self):
        super().__init__("./images/bullet1.png", 0-bullet_speed)

    def update(self):
        super().update()
        if self.rect.bottom <= SCREEN_RECT.top:
            self.kill()


